/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: CommonUtil.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.utils;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.support.design.widget.TabLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.lang.reflect.Field;

import io.bhex.app.R;
import io.bhex.app.skin.listener.NightIconFilter;
import io.bhex.app.skin.support.load.NightDrawableLoader;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.core.SPEx;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.data_manager.RateAndLocalManager;
import skin.support.SkinCompatManager;

import com.meituan.android.walle.WalleChannelReader;

public class CommonUtil {

    public static String getChannel(Context context){
        //return getAppMetaData(context, "UMENG_CHANNEL");
        String channel = WalleChannelReader.getChannel(context);
        if(TextUtils.isEmpty(channel))
            channel = "official";
        return channel;
    }


    /**
     * 获取app当前的渠道号或application中指定的meta-data
     *
     * @return 如果没有获取成功(没有对应值，或者异常)，则返回值为空
     */
    public static String getAppMetaData(Context context, String key) {
        if (context == null || TextUtils.isEmpty(key)) {
            return null;
        }
        String channelNumber = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        channelNumber = applicationInfo.metaData.getString(key);
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (TextUtils.isEmpty(channelNumber)) {
            DebugLog.w("metadata", key + " is null ");
        }
        return channelNumber;
    }


    public static String getPackageName(Context context) {
        String packName = "";
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            // 当前应用的版本名称
            //			String versionName = info.versionName;
            // 当前版本的版本号
            //			int versionCode = info.versionCode;
            // 当前版本的包名
            packName = info.packageName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return packName;
    }

    public static boolean isBhex(Context context){
        String packageName = CommonUtil.getPackageName(context);
        if (!TextUtils.isEmpty(packageName)) {
            return packageName.equals("io.bhex.app") || packageName.equals("io.bhex.app.debug") || packageName.contains("io.bhex.app.us") || packageName.contains("io.bhex.app.pre") || packageName.contains("io.bhex.app.cn");
        }else{
            return false;
        }
    }

    /**
     * 判断是不是夜间模式
     * @return
     */
    public static boolean isBlackMode(){
        return SPEx.get(AppData.SPKEY.SKIN_IS_BLACK_MODE,false);
    }

    /**
     * 默认设置成夜间模式
     */
    public static void setBlackSkin() {
        //夜间模式
        SPEx.set(AppData.SPKEY.SKIN_IS_BLACK_MODE, true);
        SkinCompatManager.getInstance().loadSkin("night",
                NightIconFilter.getInstance(),
                NightDrawableLoader.SKIN_LOADER_STRATEGY_NIGHT_DRAWABLE);

    }

    /**
     * 关闭夜间模式
     */
    public static void clearBlackSkin() {
        //夜间模式
        SPEx.set(AppData.SPKEY.SKIN_IS_BLACK_MODE, false);
        SkinCompatManager.getInstance().loadSkin("",
                NightIconFilter.getInstance(),
                SkinCompatManager.SKIN_LOADER_STRATEGY_NONE);
    }

    /**
     * 复制文本
     * @param context
     * @param copyContent
     */
    public static void copyText(Context context,String copyContent){
        if (!TextUtils.isEmpty(copyContent)) {
            // 得到剪贴板管理器
            ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            cmb.setText(copyContent);
//        ToastUtils.showShort(context, context.getResources().getString(R.string.string_copy_format,copyContent));
            ToastUtils.showShort(context, copyContent);
        }
    }

    /**
     * 粘贴
     * @param context
     * @return
     */
    public static String pasteText(Context context){
        final ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData data = cm.getPrimaryClip();
        //  ClipData 里保存了一个ArryList 的 Item 序列， 可以用 getItemCount() 来获取个数
        if (data.getItemCount()>0) {
            ClipData.Item item = data.getItemAt(0);
            return item.getText().toString();// 注意 item.getText 可能为空
        }else{
            return "";
        }
    }

    /**
     * 设置tablayout宽度
     * @param tabLayout
     * @param marginLeftDp
     * @param marginRightDp
     */
    public static void setUpIndicatorWidthByReflex(final TabLayout tabLayout, final int marginLeftDp, final int marginRightDp){
        //了解源码得知 线的宽度是根据 tabView的宽度来设置的
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到tabLayout的mTabStrip属性
                    LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);

                    int marginLeft = PixelUtils.dp2px(marginLeftDp);
                    int marginRight = PixelUtils.dp2px(marginRightDp);

                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);

                        //拿到tabView的mTextView属性  tab的字数不固定一定用反射取mTextView
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);

                        TextView mTextView = (TextView) mTextViewField.get(tabView);

                        tabView.setPadding(0, 0, 0, 0);

                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }
                        int minimumWidth = (int)tabLayout.getContext().getResources().getDimension(R.dimen.dip_32);
                        if (width<minimumWidth){
                            width =minimumWidth;
                        }

                        //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width;
                        params.leftMargin = marginLeft;
                        params.rightMargin = marginRight;
                        tabView.setLayoutParams(params);

                        tabView.invalidate();
                    }

                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * 设置tablayout宽度
     * @param tabLayout
     * @param marginLeftDp
     * @param marginRightDp
     */
    public static void setUpIndicatorWidthByReflex3(final TabLayout tabLayout, final int marginLeftDp, final int marginRightDp){
        //了解源码得知 线的宽度是根据 tabView的宽度来设置的
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到tabLayout的mTabStrip属性
                    LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);

                    int marginLeft = PixelUtils.dp2px(marginLeftDp);
                    int marginRight = PixelUtils.dp2px(marginRightDp);

                    int childCount = mTabStrip.getChildCount();
                    for (int i = 0; i < childCount; i++) {
                        View tabView = mTabStrip.getChildAt(i);

                        //拿到tabView的mTextView属性  tab的字数不固定一定用反射取mTextView
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);

                        TextView mTextView = (TextView) mTextViewField.get(tabView);

                        tabView.setPadding(0, 0, 0, 0);

                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }
                        int minimumWidth = (int)tabLayout.getContext().getResources().getDimension(R.dimen.dip_32);
                        if (width<minimumWidth){
                            width =minimumWidth;
                        }
                        int rightM;
                        if (childCount>1) {
                            rightM = (mTabStrip.getMeasuredWidth() - width * childCount)/(childCount-1);
                        }else{
                            rightM = mTabStrip.getMeasuredWidth() - width;
                        }
                        //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width;
//                        if (i==0){
//                            params.leftMargin = 0;
//                            params.rightMargin = rightM;
//                        }else

                        if (i!=0 && i == childCount-1){

                        }else{
                            params.leftMargin = 0;
                            params.rightMargin = rightM;
                        }

//                        if (i==childCount-1&&childCount>1){
//                            params.rightMargin = 0;
//                        }else{
//                            params.leftMargin = marginLeft;
//                            params.rightMargin = marginRight;
//                        }
                        tabView.setLayoutParams(params);

                        tabView.invalidate();
                    }

                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * 设置tablayout宽度
     * @param tabLayout
     * @param marginLeftDp
     * @param marginRightDp
     */
    public static void setUpIndicatorWidthByReflex2(final TabLayout tabLayout, final int marginLeftDp, final int marginRightDp){
        //了解源码得知 线的宽度是根据 tabView的宽度来设置的
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到tabLayout的mTabStrip属性
                    LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);

                    int marginLeft = PixelUtils.dp2px(marginLeftDp);
                    int marginRight = PixelUtils.dp2px(marginRightDp);

                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);

                        //拿到tabView的mTextView属性  tab的字数不固定一定用反射取mTextView
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);

                        TextView mTextView = (TextView) mTextViewField.get(tabView);
                        mTextView.setSingleLine(true);

                        tabView.setPadding(marginLeft, 0, marginRight, 0);

                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }
                        int minimumWidth = (int)tabLayout.getContext().getResources().getDimension(R.dimen.dip_32);
                        if (width<minimumWidth){
                            width =minimumWidth;
                        }

                        //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width+marginLeft+marginRight;
//                        params.width = width;
//                        params.leftMargin = marginLeft;
//                        params.rightMargin = marginRight;
                        tabView.setLayoutParams(params);

                        tabView.invalidate();
                    }

                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });

    }
    /**
     * 按矩形等比裁切图片
     */
    public static Bitmap ImageCropRect(Bitmap bitmap, View rl) {
        try {
            int w = bitmap.getWidth(); // 得到图片的宽，高
            int h = bitmap.getHeight();
            int rw = rl.getMeasuredWidth();
            int rh = rl.getMeasuredHeight();
            if (w * h * rw * rh == 0)
                return null;
            float ww = 0, wh = 0;
            if (1f * w / h > 1f * rw / rh) {
                wh = h;
                ww = 1f * rw / rh * h;
            } else if (1f * w / h < 1f * rw / rh) {
                ww = w;
                wh = 1f * rh / rw * w;
            } else {
                ww = w;
                wh = h;
            }

            float retX = 0, retY = 0;
            retX = (w - ww) / 2;
            retY = (h - wh) / 2;

            //下面这句是关键
            return Bitmap.createBitmap(bitmap, (int) retX, (int) retY, (int) ww, (int) wh, null, false);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 切对应高度的图片
     */
    public static Bitmap ImageCropHeightRect(Bitmap bitmap, int mainH, int tabH) {
        try {
            int w = bitmap.getWidth(); // 得到图片的宽，高
            int h = bitmap.getHeight();

            //下面这句是关键
            return Bitmap.createBitmap(bitmap, 0, mainH, w, tabH, null, false);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 把一个bitmap压缩，压缩到指定大小
     * @param bm
     * @param width
     * @param height
     * @return
     */
    public static Bitmap scaleBitmap(Bitmap bm, float width, float height) {
        if (bm == null) {
            return null;
        }
        int bmWidth = bm.getWidth();
        int bmHeight = bm.getHeight();
        float scaleWidth = width / bmWidth;
        float scaleHeight = height / bmHeight;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        if (scaleWidth == 1 && scaleHeight == 1) {
            return bm;
        } else {
            Bitmap resizeBitmap = Bitmap.createBitmap(bm, 0, 0, bmWidth,
                    bmHeight, matrix, false);
            bm.recycle();//回收图片内存
            bm.setDensity(240);
            return resizeBitmap;
        }
    }


        /**
         *@param
         *@描述  快速模糊化处理bitmap
         *@作者  tll
         *@时间  2016/12/5 19:22
         */
    public static Bitmap fastblur(Bitmap sentBitmap, int radius) {

        Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

        if (radius < 1) {
            return (null);
        }

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int[] pix = new int[w * h];
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);

        int wm = w - 1;
        int hm = h - 1;
        int wh = w * h;
        int div = radius + radius + 1;

        int r[] = new int[wh];
        int g[] = new int[wh];
        int b[] = new int[wh];
        int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
        int vmin[] = new int[Math.max(w, h)];

        int divsum = (div + 1) >> 1;
        divsum *= divsum;
        int temp = 256 * divsum;
        int dv[] = new int[temp];
        for (i = 0; i < temp; i++) {
            dv[i] = (i / divsum);
        }

        yw = yi = 0;

        int[][] stack = new int[div][3];
        int stackpointer;
        int stackstart;
        int[] sir;
        int rbs;
        int r1 = radius + 1;
        int routsum, goutsum, boutsum;
        int rinsum, ginsum, binsum;

        for (y = 0; y < h; y++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            for (i = -radius; i <= radius; i++) {
                p = pix[yi + Math.min(wm, Math.max(i, 0))];
                sir = stack[i + radius];
                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);
                rbs = r1 - Math.abs(i);
                rsum += sir[0] * rbs;
                gsum += sir[1] * rbs;
                bsum += sir[2] * rbs;
                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }
            }
            stackpointer = radius;

            for (x = 0; x < w; x++) {

                r[yi] = dv[rsum];
                g[yi] = dv[gsum];
                b[yi] = dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (y == 0) {
                    vmin[x] = Math.min(x + radius + 1, wm);
                }
                p = pix[yw + vmin[x]];

                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[(stackpointer) % div];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi++;
            }
            yw += w;
        }
        for (x = 0; x < w; x++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            yp = -radius * w;
            for (i = -radius; i <= radius; i++) {
                yi = Math.max(0, yp) + x;

                sir = stack[i + radius];

                sir[0] = r[yi];
                sir[1] = g[yi];
                sir[2] = b[yi];

                rbs = r1 - Math.abs(i);

                rsum += r[yi] * rbs;
                gsum += g[yi] * rbs;
                bsum += b[yi] * rbs;

                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }

                if (i < hm) {
                    yp += w;
                }
            }
            yi = x;
            stackpointer = radius;
            for (y = 0; y < h; y++) {
                pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16)
                        | (dv[gsum] << 8) | dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (x == 0) {
                    vmin[y] = Math.min(y + r1, hm) * w;
                }
                p = x + vmin[y];

                sir[0] = r[p];
                sir[1] = g[p];
                sir[2] = b[p];

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[stackpointer];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi += w;
            }
        }

        bitmap.setPixels(pix, 0, w, 0, 0, w, h);
        return (bitmap);
    }

    public static String getDefaultMobileCode(Context context) {
        String mobileCode="";
        String code = RateAndLocalManager.GetInstance(context).getCurLocalKind().code;
        if (code.equals(RateAndLocalManager.LocalKind.zh.code)) {
            mobileCode = "86";
        }else if (code.equals(RateAndLocalManager.LocalKind.en.code)) {
            mobileCode = "65";
        }else if (code.equals(RateAndLocalManager.LocalKind.ko.code)) {
            mobileCode = "82";
        }else if (code.equals(RateAndLocalManager.LocalKind.vi.code)) {
            mobileCode = "84";
        }else if (code.equals(RateAndLocalManager.LocalKind.ja.code)) {
            mobileCode = "81";
        }else if (code.equals(RateAndLocalManager.LocalKind.tr.code)) {
            mobileCode = "90";
        }

        return mobileCode;
    }
}
